<include file="public@header" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

</head>
<body>
<div class="wrap js-check-wrap">
    <ul class="nav nav-tabs">
        <li><a href="{:url('index')}">列表</a></li>
        <li><a href="{:url('add')}">单人添加</a></li>
        <li class="active"><a href="{:url('adds')}">多人添加</a></li>
    </ul>

    <!-- 错误提示区域 -->
    <div id="errorAlert" class="thinkcmf-error">
        <i class="fas fa-exclamation-circle"></i> <span id="errorMessage"></span>
    </div>

    <form action="{:url('adds')}" method="post" class="form-horizontal js-ajax-form margin-top-20">
        <div class="row">
            <div class="col-md-12">
                <table class="table table-bordered">
                    <tr>
                        <td colspan="2">
                            <div class="thinkcmf-alert">
                                <i class="fas fa-info-circle"></i> 选择景区和日期后，系统将自动加载可用的入团选项
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <td><label class="thinkcmf-form-label"><span class="required-field">手机号</span></label></td>
                        <td>
                            <input class="form-control" type="number" name="resume_mobile" id="resume_mobile" required value="" placeholder="请填写手机号"/>
                        </td>
                    </tr>

                    <if condition="$Think.session.admin_is_operate eq 1">
                        <tr>
                            <td width="150"><label class="thinkcmf-form-label"><span class="required-field">分销商</span></label></td>
                            <td>
                                <select class="thinkcmf-form-control" id="supplierUuid" name="supplier_uuid" required>
                                    <option value="" selected >-- 请选择分销商 --</option>
                                    <volist name="detail['getApiSupplierListInfo']" id="vo">
                                        <option value="{$vo.uuid}">{$vo.supplier_title}</option>
                                    </volist>
                                </select>
                            </td>
                        </tr>
                        <else/>
                        <input type="hidden" name="supplier_uuid" value="{$detail['getApiSupplierListInfo'][0]['uuid']}">
                    </if>

                    <tr>
                        <td width="150"><label class="thinkcmf-form-label"><span class="required-field">景区</span></label></td>
                        <td>
                            <select class="thinkcmf-form-control" id="scenicSpot" name="spot_uuid" required>
                                <option value="" selected disabled>-- 请选择景区 --</option>

                                <volist name="detail['getApispotListInfo']" id="vo">
                                    <option value="{$vo.uuid}">{$vo.spot_title}</option>
                                </volist>
                            </select>
                        </td>
                    </tr>

                    <tr>
                        <td><label class="thinkcmf-form-label"><span class="required-field">日期</span></label></td>
                        <td>
                            <input type="date" class="thinkcmf-form-control" id="visitDate" name="resume_date" required>
                            <div class="form-hint"></div>
                            <div class="error-message" id="visitDateError"></div>
                        </td>
                    </tr>

                    <tr id="loadingRow" style="display: none;">
                        <td colspan="2">
                            <div class="loading" id="loadingGroups">
                                <div class="spinner-border text-primary" role="status" style="width: 2rem; height: 2rem;">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                                <p class="mt-2">正在加载可用的入团选项，请稍候...</p>
                            </div>
                        </td>
                    </tr>

                    <tr id="groupRow" style="display: none;">
                        <td><label class="thinkcmf-form-label"><span class="required-field">入团名称</span></label></td>
                        <td>
                            <select class="thinkcmf-form-control" id="tourGroup" name="project_uuid" required>
                                <option value="" selected>-- 请选择入团 --</option>
                                <!-- 动态填充 -->
                            </select>
                            <div class="form-hint"></div>
                            <div class="error-message" id="tourGroupError"></div>
                        </td>
                    </tr>

                    <tr id="visitorHeader" style="display: none;">
                        <td colspan="2">
                            <div class="section-title">
                                <i class="fas fa-users"></i> 游客信息
                            </div>
                            <div class="visitor-limit-info" id="visitorLimitInfo">
                                <i class="fas fa-info-circle"></i> 该团队最多可添加 <span id="maxVisitors">0</span> 名游客，当前已添加 <span id="currentVisitors">0</span> 名
                            </div>
                        </td>
                    </tr>

                    <tr id="visitorContainerRow" style="display: none;">
                        <td colspan="2">
                            <div id="visitorContainer">
                                <!-- 动态添加游客信息行 -->
                            </div>
                        </td>
                    </tr>

                    <tr id="addVisitorRow" style="display: none;">
                        <td colspan="2" class="text-center">
                            <button type="button" class="btn btn-default" id="addVisitor">
                                <i class="fas fa-plus-circle"></i> 添加游客
                            </button>
                            <div class="form-hint">至少需要添加一位游客信息</div>
                        </td>
                    </tr>
                </table>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary js-ajax-submit">{:lang('ADD')}</button>
                        <a class="btn btn-default" href="{:url('index')}">{:lang('BACK')}</a>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<script src="__STATIC__/js/admin.js"></script>
<script>
    // 全局变量存储团队的最大游客数量
    let maxVisitors = 0;

    document.addEventListener('DOMContentLoaded', function() {
        // 设置默认日期为明天
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate());
        const formattedDate = tomorrow.toISOString().split('T')[0];
        document.getElementById('visitDate').value = formattedDate;

        // 设置最小日期为明天
        document.getElementById('visitDate').min = formattedDate;

        // 当景区或日期变化时
        document.getElementById('scenicSpot').addEventListener('change', checkSelections);
        document.getElementById('visitDate').addEventListener('change', checkSelections);

        function checkSelections() {
            const scenicId = document.getElementById('scenicSpot').value;
            const date = document.getElementById('visitDate').value;

            if (scenicId && date) {
                // 显示加载动画
                document.getElementById('loadingRow').style.display = 'table-row';
                document.getElementById('groupRow').style.display = 'none';
                document.getElementById('visitorHeader').style.display = 'none';
                document.getElementById('visitorContainerRow').style.display = 'none';
                document.getElementById('addVisitorRow').style.display = 'none';
                document.getElementById('visitorContainer').innerHTML = '';

                // 发起AJAX请求获取团队数据
                $.ajax({
                    url: "{:url('/admin/api_project/groups')}",
                    type: "POST",
                    dataType: "json",
                    data: {
                        spot_uuid: scenicId,
                        resume_date: date
                    },
                    success: function(response) {
                        document.getElementById('loadingRow').style.display = 'none';
                        if (response.code === 1) {
                            populateTourGroups(response.data);
                            document.getElementById('groupRow').style.display = 'table-row';
                        } else {
                            showError(response.msg || '获取团队数据失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        // 隐藏加载动画
                        document.getElementById('loadingRow').style.display = 'none';
                        showError('网络错误，请稍后重试');
                        console.error('AJAX请求失败:', status, error);
                    }
                });
            }
        }

        // 填充入团选项
        function populateTourGroups(groups) {
            const select = document.getElementById('tourGroup');

            // 清空现有选项，保留第一个提示选项
            while (select.options.length > 1) {
                select.remove(1);
            }

            if (groups && groups.length > 0) {
                // 添加新的选项
                groups.forEach(function(group) {
                    const option = document.createElement('option');
                    option.value = group.uuid;
                    option.textContent = group.name;
                    option.setAttribute('data-number', group.number || 0); // 存储团队最大人数
                    select.appendChild(option);
                });
            } else {
                // 如果没有可用团队
                const option = document.createElement('option');
                option.value = "";
                option.textContent = "-- 该日期无可用团队 --";
                option.disabled = true;
                select.appendChild(option);
                showError('选择的日期没有可用团队，请选择其他日期');
            }

            // 添加入团选择事件
            select.addEventListener('change', function() {
                if (this.value && this.value !== "") {
                    // 获取选中的团队的最大人数
                    const selectedOption = this.options[this.selectedIndex];
                    maxVisitors = parseInt(selectedOption.getAttribute('data-number')) || 0;

                    // 更新游客限制信息
                    document.getElementById('maxVisitors').textContent = maxVisitors;
                    document.getElementById('currentVisitors').textContent = 0;
                    document.getElementById('visitorLimitInfo').style.display = 'block';

                    document.getElementById('visitorHeader').style.display = 'table-row';
                    document.getElementById('visitorContainerRow').style.display = 'table-row';
                    document.getElementById('addVisitorRow').style.display = 'table-row';

                    // 清空现有游客信息，只保留一个
                    document.getElementById('visitorContainer').innerHTML = '';
                    addVisitorForm();
                }
            });
        }

        // 添加游客表单
        document.getElementById('addVisitor').addEventListener('click', function() {
            const currentVisitors = document.getElementById('visitorContainer').children.length;

            // 检查是否超过最大游客数量
            if (currentVisitors >= maxVisitors) {
                showError(`该团队最多只能添加 ${maxVisitors} 名游客`);
                return;
            }

            addVisitorForm();
        });

        // 添加游客表单的函数
        function addVisitorForm() {
            const visitorId = Date.now(); // 使用时间戳作为唯一ID
            const visitorCount = document.getElementById('visitorContainer').children.length + 1;

            const visitorHtml = `
                <div class="visitor-row" id="visitor-${visitorId}">
                    <div class="visitor-header">
                        <h5><i class="fas fa-user"></i> 游客 #${visitorCount}</h5>
                        <button type="button" class="btn-remove-visitor" onclick="removeVisitor(${visitorId})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="visitor-fields">
                        <div class="form-group visitor-field visitor-field-name" style="margin-left: 0;margin-right: 0">
                            <label class="thinkcmf-form-label"><span class="required-field">姓名</span></label>
                            <input type="text" class="thinkcmf-form-control" name="visitors[${visitorId}][resume_name]" placeholder="请输入真实姓名" required>
                        </div>
                        <div class="form-group visitor-field" style="margin-left: 0;margin-right: 0">
                            <label class="thinkcmf-form-label"><span class="required-field">年龄</span></label>
                            <input type="number" class="thinkcmf-form-control" name="visitors[${visitorId}][resume_age]" min="1" max="120" placeholder="年龄" required>
                        </div>
                        <div class="form-group visitor-field" style="margin-left: 0;margin-right: 0">
                            <label class="thinkcmf-form-label"><span class="required-field">性别</span></label>
                            <select class="thinkcmf-form-control" name="visitors[${visitorId}][resume_sex]" required>
                                <option value="" selected disabled>-- 请选择 --</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div class="form-group visitor-field" style="margin-left: 0;margin-right: 0">
                            <label class="thinkcmf-form-label"><span class="required-field">证件类型</span></label>
                            <select class="thinkcmf-form-control" name="visitors[${visitorId}][id_type]" required>
                                <option value="" selected disabled>-- 请选择 --</option>
                                <option value="1">身份证</option>
                                <option value="2">护照</option>
                            </select>
                        </div>
                        <div class="form-group visitor-field visitor-field-id" style="margin-left: 0;margin-right: 0">
                            <label class="thinkcmf-form-label"><span class="required-field">证件号码</span></label>
                            <input type="text" class="thinkcmf-form-control" name="visitors[${visitorId}][resume_number]" placeholder="请输入证件号码" required>
                        </div>
                    </div>
                </div>
            `;

            document.getElementById('visitorContainer').insertAdjacentHTML('beforeend', visitorHtml);

            // 更新当前游客数量显示
            document.getElementById('currentVisitors').textContent = visitorCount;

            // 更新所有游客的编号
            updateVisitorNumbers();
        }

        // 更新游客编号
        function updateVisitorNumbers() {
            const visitors = document.getElementById('visitorContainer').children;
            for (let i = 0; i < visitors.length; i++) {
                const header = visitors[i].querySelector('.visitor-header h5');
                header.innerHTML = `<i class="fas fa-user"></i> 游客 #${i + 1}`;
            }
        }

        // 显示错误提示
        function showError(message) {
            const errorAlert = document.getElementById('errorAlert');
            const errorMessage = document.getElementById('errorMessage');
            errorMessage.textContent = message;
            errorAlert.style.display = 'block';

            // 5秒后自动隐藏错误提示
            setTimeout(() => {
                errorAlert.style.display = 'none';
            }, 5000);
        }

        // 表单提交处理
        document.querySelector('form.js-ajax-form').addEventListener('submit', function(e) {
            // 重置所有错误状态
            document.querySelectorAll('.thinkcmf-form-control.error').forEach(el => {
                el.classList.remove('error');
            });
            document.querySelectorAll('.error-message').forEach(el => {
                el.style.display = 'none';
            });
            document.getElementById('errorAlert').style.display = 'none';

            let hasError = false;
            let errorMessage = '';

            // 验证景区选择
            const supplierUuid = document.getElementById('supplierUuid');
            if (!supplierUuid.value) {
                supplierUuid.classList.add('error');
                document.getElementById('scenicSpotError').style.display = 'block';
                hasError = false;
                errorMessage = '请选择景区';
            }

            // 验证景区选择
            const scenicSpot = document.getElementById('scenicSpot');
            if (!scenicSpot.value) {
                scenicSpot.classList.add('error');
                document.getElementById('scenicSpotError').style.display = 'block';
                hasError = false;
                errorMessage = '请选择景区';
            }

            // 验证日期选择
            const visitDate = document.getElementById('visitDate');
            if (!visitDate.value) {
                visitDate.classList.add('error');
                document.getElementById('visitDateError').style.display = 'block';
                hasError = false;
                errorMessage = errorMessage || '请选择日期';
            }

            // 验证入团选择
            const tourGroup = document.getElementById('tourGroup');
            if (!tourGroup.value || tourGroup.value === "") {
                tourGroup.classList.add('error');
                document.getElementById('tourGroupError').style.display = 'block';
                hasError = false;
                errorMessage = errorMessage || '请选择入团名称';
            }

            // 验证游客信息
            const visitorForms = document.getElementById('visitorContainer').children;
            if (visitorForms.length === 0) {
                hasError = true;
                errorMessage = errorMessage || '请至少添加一位游客';
            } else {
                // 验证每个游客的表单字段
                const requiredFields = document.querySelectorAll('#visitorContainer input[required], #visitorContainer select[required]');
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        field.classList.add('error');
                        field.nextElementSibling.style.display = 'block';
                        hasError = true;
                      //  errorMessage = errorMessage || '请完善所有游客信息';
                    }
                });
            }

            if (hasError) {
                e.preventDefault();
                showError(errorMessage);

                // 滚动到第一个错误字段
                const firstError = document.querySelector('.thinkcmf-form-control.error');
                if (firstError) {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            }
        });
    });

    // 移除游客表单
    function removeVisitor(id) {
        const visitorContainer = document.getElementById('visitorContainer');
        if (visitorContainer.children.length > 1) {
            document.getElementById(`visitor-${id}`).remove();

            // 更新当前游客数量显示
            document.getElementById('currentVisitors').textContent = visitorContainer.children.length;

            // 更新剩余游客的编号
            const visitors = visitorContainer.children;
            for (let i = 0; i < visitors.length; i++) {
                const header = visitors[i].querySelector('.visitor-header h5');
                header.innerHTML = `<i class="fas fa-user"></i> 游客 #${i + 1}`;
            }
        } else {
            showError('至少需要保留一位游客信息！');
        }
    }
</script>
<style>
    :root {
        --primary-color: #2c7be5;
        --secondary-color: #6c757d;
        --success-color: #00d97e;
        --light-bg: #f8f9fa;
        --border-color: #e9ecef;
    }

    .wrap {
        width: 100%;
        max-width: 100%;
    }

    .table {
        width: 100%;
    }

    .thinkcmf-form-label {
        font-weight: 600;
        color: #344050;
        margin-bottom: 8px;
        display: block;
        font-size: 14px;
    }

    .thinkcmf-form-control {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid var(--border-color);
        border-radius: 4px;
        transition: all 0.2s;
        font-size: 14px;
        height: 40px;
    }

    .thinkcmf-form-control:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.2rem rgba(44, 123, 229, 0.25);
        outline: none;
    }

    .thinkcmf-form-control.error {
        border-color: #e63757;
        box-shadow: 0 0 0 0.2rem rgba(230, 55, 87, 0.25);
    }

    .form-group {
        margin-bottom: 15px;
    }

    .visitor-row {
        border: 1px solid #e9ecef;
        border-radius: 8px;
        margin-bottom: 20px;
        padding: 20px;
        background-color: #fff;
        position: relative;
        transition: all 0.3s ease;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    }

    .visitor-row:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        border-color: var(--primary-color);
    }

    .btn-remove-visitor {
        position: absolute;
        top: 15px;
        right: 15px;
        color: #e63757;
        background: transparent;
        border: none;
        font-size: 18px;
        cursor: pointer;
        padding: 5px;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .btn-remove-visitor:hover {
        color: #fff;
        background-color: #e63757;
    }

    .loading {
        text-align: center;
        padding: 30px;
        background-color: var(--light-bg);
        border-radius: 8px;
        margin: 20px 0;
        display: none;
    }

    .section-title {
        border-bottom: 2px solid var(--primary-color);
        padding-bottom: 10px;
        margin-bottom: 20px;
        color: #344050;
        font-weight: 600;
        margin-top: 30px;
        font-size: 18px;
    }

    .thinkcmf-alert {
        border-radius: 8px;
        padding: 15px 20px;
        margin-bottom: 25px;
        background-color: #e1f0ff;
        border: 1px solid #b3d7ff;
        color: #0066cc;
    }

    .thinkcmf-error {
        border-radius: 8px;
        padding: 15px 20px;
        margin-bottom: 25px;
        background-color: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
        display: none;
    }

    .text-danger {
        color: #e63757;
    }

    .visitor-header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px dashed #e9ecef;
    }

    .visitor-header h5 {
        margin: 0;
        font-size: 16px;
        color: var(--primary-color);
        flex-grow: 1;
    }

    .visitor-fields {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
    }

    .visitor-field {
        flex: 1;
        min-width: 120px;
    }

    .visitor-field-name {
        flex: 1.5;
        min-width: 150px;
    }

    .visitor-field-id {
        flex: 2;
        min-width: 200px;
    }

    .required-field::after {
        content: "*";
        color: #e63757;
        margin-left: 3px;
    }

    .form-hint {
        font-size: 12px;
        color: var(--secondary-color);
        margin-top: 5px;
    }

    .error-message {
        color: #e63757;
        font-size: 12px;
        margin-top: 5px;
        display: none;
    }

    .visitor-limit-info {
        background-color: #f8f9fa;
        border-radius: 6px;
        padding: 10px 15px;
        margin-bottom: 15px;
        border-left: 4px solid var(--primary-color);
        display: none;
    }

    @media (max-width: 992px) {
        .visitor-fields {
            flex-direction: column;
        }

        .visitor-field {
            width: 100%;
        }

        .visitor-row {
            padding: 15px;
        }
    }
</style>
</body>
</html>